package nl.master.ledonoffadk;

import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
 
import com.android.future.usb.UsbAccessory;
import com.android.future.usb.UsbManager;
 
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageButton;
import android.widget.ToggleButton;
 
public class LEDonoffActivity extends Activity {
    private static final String TAG = "NaLa Master";
  
    // Intent Action Name of this Application
    private static final String ACTION_USB_PERMISSION
                = "ca.blogspot.LEDonoffADK.action.USB_PERMISSION";
 
    private PendingIntent mPermissionIntent;
    private boolean mPermissionRequestPending;
  
    private UsbManager mUsbManager;
    private UsbAccessory mAccessory;
 
    ParcelFileDescriptor mFileDescriptor;
 
    static FileOutputStream mOutputStream;
 
    //Instance of ToggleButton in layout
    private ToggleButton mToggleButtonRed;
    private ToggleButton mToggleButtonGreen;
    private ToggleButton mToggleButtonBlue;
    private ToggleButton mToggleButtonPad;
    private ImageButton mButtonVideo;
    
    private String red = "000";
    private String green = "000";
    private String blue = "000";
 
    //Instance mUsbReceiver to monitor USB broadcast
    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
 
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //ACTION_USB_PERMISSION
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    // Grt Accessory from Intent 
                    UsbAccessory accessory = UsbManager.getAccessory(intent);
                    //in dialogue OK=true, Cancel=false
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        openAccessory(accessory);
                    } else {
                        Log.d(TAG, "permission denied for accessory " + accessory);
                    }
                    mPermissionRequestPending = false;
                }
            //When USB host shield is disconnected from USB connector
            } else if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {
                UsbAccessory accessory = UsbManager.getAccessory(intent);
                // is it USB accessory connected?
                if (accessory != null && accessory.equals(mAccessory)) {
                    // if USB accessory having been connected, then close
                    closeAccessory();
                }
            }
        }
 
    };
 
    //Processing at Start OnCreate() （Activity life cycle）
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        // instance UsbManager
        mUsbManager = UsbManager.getInstance(this);
 
        // Make permission Intent of own Application
        mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION),0);
 
        // Register Broadcast Receiver's Intent
        IntentFilter filter = new IntentFilter();
        //Intent filter for USB Accessory connect/disconnect
        filter.addAction(ACTION_USB_PERMISSION);
        //Intent filter for USB Accessory detached
        filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
        registerReceiver(mUsbReceiver, filter);
 
        // Set up layout at layout/main.xml
        setContentView(R.layout.main);
        
      
        
        // make instance mToggleButton1
        mToggleButtonRed = (ToggleButton) findViewById(R.id.toggleButton1);
        //Toggle Button 
        mToggleButtonRed.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                red =  (isChecked ? "255" : "000");
          
            	 sendCommand(("l0" + red + green + blue).getBytes());  
            	 sendCommand(("l1" + red + green + blue).getBytes());
            	 sendCommand(("l2" + red + green + blue).getBytes());
            	 sendCommand(("l3" + red + green + blue).getBytes());
            }
        });
        
        mToggleButtonGreen = (ToggleButton) findViewById(R.id.toggleButton2);     
        mToggleButtonGreen.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            	green =  (isChecked ? "255" : "000");
            	sendCommand(("l0" + red + green + blue).getBytes());
            	sendCommand(("l1" + red + green + blue).getBytes());
            	sendCommand(("l2" + red + green + blue).getBytes());
            	sendCommand(("l3" + red + green + blue).getBytes());
            }
        });
        
        mToggleButtonBlue = (ToggleButton) findViewById(R.id.toggleButton3);
        mToggleButtonBlue.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            	 blue =  (isChecked ? "255" : "000");
                 
              	 sendCommand(("l0" + red + green + blue).getBytes());  
              	 sendCommand(("l1" + red + green + blue).getBytes());
              	 sendCommand(("l2" + red + green + blue).getBytes());
              	 sendCommand(("l3" + red + green + blue).getBytes());
            }
        });
        
      
        
     /*   mToggleButtonPad = (ToggleButton) findViewById(R.id.toggleButton4);     
        mToggleButtonPad.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            	String command =  (isChecked ? "pl1" : "pl0");
            	sendCommand(command.getBytes());
            }
        });*/
        
        mButtonVideo = (ImageButton) findViewById(R.id.toggleButtonVideo1);
        mButtonVideo.setOnClickListener(new OnClickListener()	{
        	public void onClick(View v){     		
        		Intent intent  = (new Intent (LEDonoffActivity.this, MediaPlayer.class));
        		intent.putExtra("videoname", "/MediaTab/one.mp4");
        		startActivity(intent);
        	}
        });
        
        mButtonVideo = (ImageButton) findViewById(R.id.toggleButtonVideo2);
        mButtonVideo.setOnClickListener(new OnClickListener()	{
        	public void onClick(View v){     		
        		Intent intent  = (new Intent (LEDonoffActivity.this, MediaPlayer.class));
        		intent.putExtra("videoname", "/MediaTab/two.mp4");
        		startActivity(intent);
        	}
        });
        mButtonVideo = (ImageButton) findViewById(R.id.toggleButtonVideo3);
        mButtonVideo.setOnClickListener(new OnClickListener()	{
        	public void onClick(View v){     		
        		Intent intent  = (new Intent (LEDonoffActivity.this, MediaPlayer.class));
        		intent.putExtra("videoname", "/MediaTab/three.mp4");
        		startActivity(intent);
        	}
        });
        mButtonVideo = (ImageButton) findViewById(R.id.toggleButtonVideo4);
        mButtonVideo.setOnClickListener(new OnClickListener()	{
        	public void onClick(View v){     		
        		Intent intent  = (new Intent (LEDonoffActivity.this, MediaPlayer.class));
        		intent.putExtra("videoname", "/MediaTab/four.mp4");       		
        		startActivity(intent);
        	}
        });
        
    }
 
    
    @Override
    public void onResume() {
        super.onResume();
 
        //if already communicating
        if (mOutputStream != null) {
            return;
        }
 
        // Check if any USB accessory is connected
        UsbAccessory[] accessories = mUsbManager.getAccessoryList();
        UsbAccessory accessory = (accessories == null ? null : accessories[0]);
        if (accessory != null) {
            // check if permission to USB Accessory is granted
            if (mUsbManager.hasPermission(accessory)) {
                // if permitted, start accessory access
                openAccessory(accessory);
            } else {
                // if not permitted, send permission intent
                synchronized (mUsbReceiver) {
                    if (!mPermissionRequestPending) {
                        // Ask for permission
                        mUsbManager.requestPermission(accessory, mPermissionIntent);
                        mPermissionRequestPending = true;
                    }
                }
            }
        } else {
            Log.d(TAG, "mAccessory is null");
        }
    }
 

    @Override
    public void onPause() {
        super.onPause();
        //closeAccessory();
    }
 

    @Override
    public void onDestroy() {
    	Log.i(TAG, "im Destroy, ausschalten aller LEDs und PADs");
    	sendCommand("l0000000000l1000000000l2000000000l3000000000".getBytes());
    	sendCommand("pl0".getBytes());
    	sendCommand("off".getBytes());
        unregisterReceiver(mUsbReceiver);
        super.onDestroy();
    }
 
    //Open USB Accessory
    private void openAccessory(UsbAccessory accessory) {
        // Get descriptor of Accessory
        mFileDescriptor = mUsbManager.openAccessory(accessory);
 
        if (mFileDescriptor != null) {
            mAccessory = accessory;
            FileDescriptor fd = mFileDescriptor.getFileDescriptor();
            mOutputStream = new FileOutputStream(fd);
            Log.d(TAG, "accessory opened");
        } else {
            Log.d(TAG, "accessory open fail");
        }
    }
 
    // Close USB Accessory
    private void closeAccessory() {
 
        try {
            if (mFileDescriptor != null) {
                mFileDescriptor.close();
            }
        } catch (IOException e) {
        } finally {
            mFileDescriptor = null;
            mAccessory = null;
        }
    }
 
    // Output from Android（USB Accessory）-> Arduino（USB Host）
    public static void sendCommand(byte[] value) {
       
        if (mOutputStream != null) {
            try {
                mOutputStream.write(value);
                //Log.i(TAG, "Send: " + value + '\n');
            	//mOutputStream.write(test.getBytes());
            } catch (IOException e) {
                Log.e(TAG, "sendCommand:write failed", e);
            }
        }
    }
}
